package com.atguigu.gmall.common.config.exception.handler;

import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tangsy
 * @Description TODO
 * @date 2022/12/11 12:42
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({GmallException.class})
    public Result handleGmallException(GmallException e){
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return fail;
    }

    @ExceptionHandler({Exception.class})
    public Result handleException(Exception e){
        Result<Object> fail = Result.fail();
        fail.setMessage(e.getMessage());
        return fail;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        Result<Object> fail = Result.fail();
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errMap = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()){
            String field = error.getField();
            String defaultMessage = error.getDefaultMessage();
            errMap.put(field,defaultMessage);
        }

        return Result.build(errMap, ResultCodeEnum.INVAILD_PARAM);
    }

}
